package se.lth.student.axisandroidcam.client.cameraclients;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import se.lth.student.axisandroidcam.client.AxisAndroidCamera;
import se.lth.student.axisandroidcam.client.Camera;
import se.lth.student.axisandroidcam.client.DataWrapper;
import se.lth.student.axisandroidcam.client.SynchronizeThread;
import se.lth.student.axisandroidcam.client.Toolbox;

import android.app.Activity;

public class NetworkClientIn extends ClientIn {
	private String serverAddress;
	private Socket clientSocket;
	private SynchronizeThread synchThread;

	public NetworkClientIn(int cam, Activity activity, 
			String serverAddress, SynchronizeThread synchThread) {
		super(cam, activity);
		this.serverAddress = serverAddress;
		this.synchThread = synchThread;
	}

	@Override
	public void run() {
		Toolbox.printDebug("Starting Client In");
		try {
			Toolbox.printDebug("NetworkIn: Trying to connect to: " + serverAddress);
			clientSocket = new Socket(serverAddress, AxisAndroidCamera.PORT
					+ (super.cameraNumber * 10));
			
			InputStream in = clientSocket.getInputStream();
			Toolbox.printDebug("NetworkIn: Got stream to: " + serverAddress);
		    DataInputStream dis = new DataInputStream(in);						
		    while(true){
		    	int  len = dis.readInt();		    
		    	final boolean isMovie = dis.readBoolean();
		    	Toolbox.printDebug("NetworkIn: Found picture, size: "+len);
		        final byte[] data = new byte[len];
		        if (len > 0) {
		            dis.readFully(data);
		            Toolbox.printDebug("NetworkIn: Read picture!");
		            DataWrapper wrap = new DataWrapper(data, cameraNumber, isMovie);
		            synchThread.addImage(wrap);
		        }
		    }
		} catch (IOException e1) {
			Toolbox.printDebug("NetworkIn: Failed to connect to: " + serverAddress);
			e1.printStackTrace();
		}
	}
}
